<template>
  <MkDialogEdit ref='dialogRef' v-model:isEdit='ctx.isEdit' @submit='submit'>
    <MkForm :model='ctx.entity' ref='formRef' formId='BasXueYeChanPinFeiYong'>
      <MkInput label='名称' v-model='ctx.entity.mingCheng' prop='mingCheng' :isEdit='ctx.isEdit' />
      <MkInput label='备注' v-model='ctx.entity.remark' prop='remark' :isEdit='ctx.isEdit' />
      <MkIsEnabled v-model='ctx.entity.isEnabled' :isEdit='ctx.isEdit' />
    </MkForm>
  </MkDialogEdit>
</template>

<script lang='ts' setup>
import { BasXueYeChanPinFeiYongApi, BasXueYeChanPinFeiYongOutput } from '/@/api/bas/BasXueYeChanPinFeiYong';
import { isNull, clog } from '/@/utils';

const emits = defineEmits(['query'])
const ctx = reactive({
  isEdit: false,
  entity: {} as BasXueYeChanPinFeiYongOutput,
});

const dialogRef = ref();
const formRef = ref();

/** 打开弹框 */
const open = async (row: BasXueYeChanPinFeiYongOutput) => {
  dialogRef.value.show();
  if (isNull(row?.id)) {
    ctx.isEdit = true;
    ctx.entity = { isEnabled: true } as BasXueYeChanPinFeiYongOutput;
  } else {
    ctx.isEdit = false;
    ctx.entity = JSON.parse(JSON.stringify(row));
  }
};

const close = () => {
  dialogRef.value?.close();
  emits('query')
};

const submit = async () => {
  if (!ctx.isEdit) {
    close();
    return;
  }
  // 表单验证
  const validate = await formRef?.value?.validate();
  if (!validate) return;
  if (isNull(ctx.entity.id)) {
    await BasXueYeChanPinFeiYongApi.add(ctx.entity);
  } else {
    await BasXueYeChanPinFeiYongApi.update(ctx.entity);
  }
  close();
};

defineExpose({ open })
</script>